import React from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Edit, Trash2, Shield, AlertTriangle } from "lucide-react";

export default function SafetyRiskPointCard({ riskPoint, onEdit, onDelete }) {
  const {
    riskCode,
    riskName,
    riskType,
    primaryCategory,
    secondaryCategory,
    tertiaryCategory,
    riskDescription,
    controlMeasures,
    baseRiskLevel,
    baseRiskValue,
    baseLikelihood,
    baseConsequence,
    baseExposure,
  } = riskPoint;

  const riskLevelColors = {
    veryLow: "bg-green-100 text-green-800 border-green-200",
    low: "bg-blue-100 text-blue-800 border-blue-200",
    medium: "bg-yellow-100 text-yellow-800 border-yellow-200",
    high: "bg-orange-100 text-orange-800 border-orange-200",
    veryHigh: "bg-red-100 text-red-800 border-red-200",
  };

  const riskLevelLabels = {
    veryLow: "极低",
    low: "低",
    medium: "中",
    high: "高",
    veryHigh: "极高",
  };

  const riskTypeLabels = {
    mechanical: "机械",
    electrical: "电气",
    chemical: "化学",
    physical: "物理",
    environmental: "环境",
    behavioral: "行为",
    organizational: "管理",
    poisoning: "中毒",
    suffocation: "窒息",
    tripFall: "摔绊",
    fall: "坠落",
    fallFromHeight: "高处坠落",
    struckByObject: "物体打击",
    strike: "打击",
    sprain: "扭伤",
    burn: "烧伤",
    burnFire: "烧伤（引起火灾）",
    scald: "灼伤",
    scaldBurn: "灼（烫）伤",
    electricShock: "触电",
    personalElectricShock: "人身触电",
    equipmentTrip: "设备跳闸",
    equipmentDamage: "设备损坏",
    equipmentBreakdown: "设备破损",
    equipmentShutdown: "设备停运",
    equipmentPowerOutage: "停电",
    equipmentBurn: "设备烧损",
    partialPowerOutage: "局部停电",
    fire: "火灾",
    explosion: "爆炸",
    collapse: "坍塌",
    landslide: "塌方",
    drowning: "溺水",
    drowningAlt: "淹溺",
    stab: "刺伤",
    cut: "割伤",
    clip: "夹伤",
    entanglement: "绞伤",
    mechanicalInjury: "机械伤害",
    lungDysfunction: "肺功能障碍",
    occupationalDisease: "职业病",
    crash: "碰撞",
    crushInjury: "压伤",
    socialResponsibility: "社会责任",
    personalCasualty: "人身伤亡",
    frameOverturn: "架体倾覆",
    trafficAccident: "交通意外",
  };

  const getCategoryLabel = (cat) => {
    const labels = {
      foundations: "基础施工",
      towerAssembly: "杆塔组立",
      stringingWorks: "架线工程",
      liveLineWork: "带电作业",
      transportation: "物料运输",
    };
    return labels[cat] || cat;
  };

  // 获取单个风险类型的显示文本
  const getSingleRiskTypeLabel = (type) => {
    if (!type || typeof type !== "string") {
      return "未分类";
    }
    return riskTypeLabels[type] || `其他(${type})`;
  };

  // 处理数组类型的风险类型
  const getRiskTypeLabels = (types) => {
    const typeArray = Array.isArray(types) ? types : [types];
    return typeArray
      .filter((type) => type) // 过滤空值
      .map((type) => getSingleRiskTypeLabel(type));
  };

  const riskTypes = getRiskTypeLabels(riskType);

  return (
    <Card className="shadow-md hover:shadow-xl transition-shadow duration-300" >
      <CardHeader className="flex flex-row items-start justify-between pb-2">
        <div className="space-y-2 flex-1">
          <div className="flex flex-row items-start justify-between pb-2  md:grid-cols-2">
            <CardTitle className="text-base font-bold leading-tight">
              {riskName ||
                (riskDescription
                  ? riskDescription.substring(0, 30) + "..."
                  : "无名称")}
            </CardTitle>
            <div className="flex md:grid-cols-2">
              <Button
                variant="ghost"
                size="icon"
                className="w-7 h-7"
                onClick={() => onEdit(riskPoint)}
              >
                <Edit className="w-4 h-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="w-7 h-7"
                onClick={() => onDelete(riskPoint.id)}
              >
                <Trash2 className="w-4 h-4 text-red-500" />
              </Button>
            </div>
          </div>

          <div>
            <Badge className="bg-purple-100 text-purple-800 text-xs px-2 py-1 flex flex-wrap gap-x-2 gap-y-1  hover:bg-purple-200 ">
              {riskTypes.map((label, index) => (
                <div
                  key={index}
                  style={{
                    marginRight: index < riskTypes.length - 1 ? "6px" : 0,
                  }}
                >
                  {label}
                </div>
              ))}
            </Badge>
          </div>

          <div className="flex items-center gap-2">
            <Badge
              className={riskLevelColors[baseRiskLevel]}
              style={{ fontSize: "0.75rem" }}
            >
              {riskLevelLabels[baseRiskLevel]?.toUpperCase()} (R={baseRiskValue}
              )
            </Badge>
            <div className="text-xs text-gray-500">
              L={baseLikelihood} × C={baseConsequence} × E={baseExposure}
            </div>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        <div className="space-y-3">
          <div className="text-xs text-gray-600">
            <div>类别: {getCategoryLabel(primaryCategory)}</div>
            {secondaryCategory && <div>子类: {secondaryCategory}</div>}
            {tertiaryCategory && <div>细分: {tertiaryCategory}</div>}
          </div>

          <p className="text-sm text-gray-700 line-clamp-2">
            {riskDescription}
          </p>

          <div className="space-y-2">
            <h4 className="text-sm font-semibold flex items-center gap-1">
              <Shield className="w-4 h-4 text-blue-600" />
              控制措施:
            </h4>
            <ul className="list-disc list-inside text-sm text-gray-700 space-y-1">
              {(controlMeasures || []).slice(0, 3).map((measure, index) => (
                <li key={index} className="line-clamp-1">
                  {measure}
                </li>
              ))}
              {(controlMeasures?.length || 0) > 3 && (
                <li className="text-gray-500">
                  ...等共 {controlMeasures.length} 项
                </li>
              )}
            </ul>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
